<template>
  <el-dialog
    style="width: 100%;"
    title="导入题目"
    :append-to-body="true" :close-on-click-modal="false"
    :visible.sync="visible"
    @open="openLoad"
    @close="dialogClose"
  >
    <div style="height: 300px;" v-loading="loading">
       <el-form :model="formFile" :inline="true"  label-width="120px" style="margin: 5px;">
<!--          <el-row  v-if="data.bankId!=='0'">
             <el-col :span="24"  style="height: 50px;">
               <el-form-item label="选择专业" class="dd-label" prop="majorId">
                <treeselect v-model="majorId" class="treeselect-main" style="width: 500px;" :disable-branch-nodes="true" :normalizer="normalizer"
                            :options="specialty" placeholder="选择专业"/>
               </el-form-item>
             </el-col>
           </el-row> -->
           <el-row>
              <el-col :span="24"  style="height: 50px;">
                <el-form-item label="题目文件" class="dd-label" prop="题目">
                  <el-upload style="width: 500px;"
                    ref="upload"
                    :action="uploadUrl"
                    :file-list="fileList"
                    class="upload-demo"
                    :headers="headers"
                    :limit="1"
                    :data="data"
                    :accept="accept"
                    :before-upload="beforeCheck"
                    :on-exceed="handleExceed"
                    :on-change="submitUpload"
                    :on-error="errorUpload"
                    :on-success="successUpload"
                    :auto-upload="false">
                    <el-button
                      style="margin: 5px !important"
                      slot="tip"
                      type="danger"
                      icon="el-icon-download"
                      @click.stop="download">下载模板
                    </el-button>
                    <el-button slot="trigger" icon="el-icon-circle-plus-outline" type="warning">选择导入文件</el-button>
                    <div slot="tip" class="el-upload__tip" style="font-size: 14px;">tips:请先填写题库模板后再上传文件。</div>
                    <div v-if="showTips" slot="tip" class="el-upload__tip" style="color: red;font-size: 14px;">提示：模板已下载至程序源文件路径下的“Table template”文件夹中，
                    请编辑后再上传(*提示:编辑后的表格记得及时修改文件名称，以免下次下载模板被误覆盖。)</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
       </el-form>
    </div>
  </el-dialog>
</template>

<script>
  import { downloadTemplate, importExcel } from '@/api/business/questionBank'
  import { getToken } from '@/utils/auth'
  import { tree } from '@/api/framework/system/specialty'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    components: { Treeselect },
    props: {
      data: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        loading:false,
        showTips:false,
        formFile:{},
        keyWords: '',
        fileList: [],
        specialty: [],
        uploadUrl: importExcel,
        errorInfo: false,
        majorId: null,
        headers: {
          'Authorization': 'Bearer ' + getToken()
        }
      }
    },
    computed: {
      accept() {
        return '.xls,.xlsx'
      }
    },
    methods: {
      openLoad() {
        //this.getSpecialtyType()
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
      },
      getSpecialtyType() {
        tree().then(data => {
          this.specialty = []
          const type = { id: '0', label: '题库专业分类', children: [] }
          type.children = data
          this.specialty.push(type)
        })
      },
      submitUpload() {
        this.$refs.upload.submit()
        //this.loading=false
      },
      handleExceed(files, fileList) {
        this.$message.error(
          `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        )
      },
      successUpload(response, file, fileList) {
        this.$message.success('上传成功')
        this.loading=false
        this.visible=false;//关闭窗口
        this.$refs.upload.clearFiles();//清除文件
        this.majorId=null;
        this.$parent.init()
        if (this.data.bankId === '0') {
          const questionInfo = []
          const user = { bankId: response.id, bankName: response.bankName, bankDesc: response.bankDesc }
          questionInfo.push(user)
          this.$emit('setQuestionInfo', questionInfo)
        }
      },
      errorUpload(err, file, fileList) {
        this.loading=false
        this.$message.error('上传失败,请检查模板是否正确填写或稍后重试')
      },
      download() {
        this.showTips=true
        window.location.href = downloadTemplate
        //this.$message.error('模板已下载至程序源文件路径下的“Table template”文件夹中，请编辑后再上传(*提示:编辑后的表格记得及时修改文件名称，以免下次下载模板被误覆盖)')
        // this.$confirm('模板已下载至程序源文件路径下的“Table template”文件夹中，请编辑后再上传(*提示:编辑后的表格记得及时修改文件名称，以免下次下载模板被误覆盖)', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   showCancelButton: false,//不显示取消按钮
        //   type: 'warning'
        // })
      },
      downloadError() {
        error({})
          .then(() => {
            this.$message.success('下载成功')
            this.errorInfo = false
          })
          .catch(err => {
            this.$message.error(err.message)
            this.errorInfo = false
          })
      },
      dialogClose() {
        this.showTips=false
        this.$refs.upload.clearFiles()
      },
      // 上传文件之前
      beforeCheck(file) {
        this.loading=true
        // if (this.majorId == null && this.data.bankId!=='0') {
        //   this.$message.error('请选择专业类别！')
        //   this.loading=false
        //   return false
        // }
        this.data.majorId = this.majorId
        let strArr = file.name.split('.')
        let bType = '.' + strArr[strArr.length - 1]
        if (this.accept.indexOf(bType) === -1) {
          this.$message.error('文件格式不正确请重新选择！')
          this.loading=false
          return false
        }
        return true
      }
    }
  }
</script>
<style scoped>

  .treeselect-main {
    margin-top: 1px;
    width: 500px;
    line-height: 35px;

  .vue-treeselect__placeholder {
    line-height: 35px;
  }

  .vue-treeselect__control {
    height: 36px;
  }

  }
</style>
